package demo.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class GeneraeCode {

	private static FileReader fileReader;
	private static BufferedReader bufferedReader;
	private static FileWriter fileWriter;
	private static Scanner scanner = new Scanner(System.in);

	private final static String PATH_DAO = "java/demo/dao/";
	private final static String PATH_DAO_IMPL = "java/demo/dao/impl/";
	private final static String PATH_SERVICE = "java/demo/service/";
	private final static String PATH_SERVICE_IMPL = "java/demo/service/impl/";
	private final static String PATH_ENTITY = "java/demo/entity/";
	private final static String PATH_STRUTS = "resources/conf/struts/";
	private final static String PATH_ACTION = "java/demo/action/";
	private final static String PATH_HBM = "resources/conf/hibernate/hbm/";
	private final static String PATH_SPRING = "resources/conf/spring/";

	private static void generate(String template, String path, String x, String y) throws IOException {
		fileReader = new FileReader("resources/template/code/" + template + ".txt");
		bufferedReader = new BufferedReader(fileReader);
		StringBuffer stringBuffer = new StringBuffer();
		String string;
		while ((string = bufferedReader.readLine()) != null) {
			string = string.replaceAll("XXX", x);
			string = string.replaceAll("YYY", y);
			stringBuffer.append(string + "\n");
		}
		bufferedReader.close();
		fileReader.close();
		
		String filename;
		if(template.equals("Entity")) {
			filename = x + ".java";
		} else if(template.equals("struts")) {
			filename = "struts-" + x + ".xml";
		} else if(template.equals("hbm")) {
			filename = x + ".hbm.xml";
		} else if(template.equals("spring")) {
			filename = "beans-" + y + ".xml";
		} else {
			filename = x + template + ".java";
		}
		fileWriter = new FileWriter(path + filename);
		fileWriter.write(stringBuffer.toString());
		System.out.println("\t" + filename + "生成!");
		fileWriter.flush();
		fileWriter.close();
	}

	public static void main(String[] args) throws IOException {
		System.out.println("请输入实体类名（如User）：");
		String entity = scanner.nextLine();
		System.out.println("请输入主键类型（如Long）：");
		String id = scanner.nextLine();

		generate("Dao", PATH_DAO, entity, id);//Dao
		generate("DaoImpl", PATH_DAO_IMPL, entity, id);//DaoImpl
		generate("Service", PATH_SERVICE, entity, id);//Service
		generate("ServiceImpl", PATH_SERVICE_IMPL, entity, id);//ServiceImpl
		generate("Entity", PATH_ENTITY, entity, "");//Entity
		generate("struts", PATH_STRUTS, entity.toLowerCase(), "");//Struts
		generate("Action", PATH_ACTION, entity, entity.toLowerCase());//Action
		generate("hbm", PATH_HBM, entity, "");//hbm
		generate("spring", PATH_SPRING, entity, entity.toLowerCase());//Spring

		System.out.println("请更新java和resources文件夹");
	}

}
